#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QStringListModel>
#include <QStringList>
#include <QMessageBox>
#include <QTimer>
/*
 * date: 2023/8/17
 * author: brook
 * description: initialize the player
*/
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::StrongFocus);
    m_pausecount = 0;
    m_totalSeconds = 0;
    m_audiovolume_record = 0;
    m_audiobutton_count = 0;
    m_vp_entrance = VpEntrance::getInstance();
//    connect(m_vp, SIGNAL(sendImage(uint8_t*,int,int)), ui->Widshow, SLOT(showImage(uint8_t*,int,int)));
    connect(m_vp_entrance, SIGNAL(sendImage(uint8_t*,int,int)), ui->Widshow, SLOT(showImage(uint8_t*,int,int)));
    connect(m_vp_entrance, SIGNAL(sendSeconds(int)), ui->SldVideoSlider, SLOT(getseconds(int)));
    connect(m_vp_entrance, SIGNAL(sendSeconds(int)), this, SLOT(setSeconds(int)));
    connect(m_vp_entrance, SIGNAL(sendAllSeconds(int)), ui->SldVideoSlider, SLOT(getAllSeconds(int)));
    connect(m_vp_entrance, SIGNAL(sendAllSeconds(int)), this, SLOT(setAllSeconds(int)));
    connect(ui->SldVideoSlider, SIGNAL(sendTargetTime(int)), m_vp_entrance, SLOT(seek_time(int)));
    connect(this, SIGNAL(sendTargetTime(int)), m_vp_entrance, SLOT(seek_time(int)));
    connect(ui->SldVolume, SIGNAL(sendTargetAudioVolume(int)), m_vp_entrance, SLOT(set_audio_volume(int)));
//    connect(m_vp, SIGNAL(sendCurSeconds(int)), ui->SldVideoSlider, SLOT(getseconds(int)));
//    connect(m_vp, SIGNAL(sendCurSeconds(int)), this, SLOT(alterCurSeconds(int)));
//    connect(ui->SldVideoSlider, SIGNAL(sendTargetTime(int)), m_vp, SLOT(seek_to_time(int)));
//    connect(ui->SldVolume, SIGNAL(sendTargetAudioVolume(int)), m_vp, SLOT(set_audiovolume(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

/*
 * date: 2023/8/15
 * author: brook
 * description: add a video file into fileinfo list
*/
void MainWindow::addfile()
{
    QString fileName =  QFileDialog::getOpenFileName(  this,
                            "选择多媒体文件",
                            "/home",
                            "多媒体文件 (*.mp4 *.avi *.mkv *.mp3 *.aac *.mov *.ts)" );
    if (fileName.isEmpty())
        return;
    if(m_vecString.contains(fileName))
        return;
    QFileInfo fileinfo;
    fileinfo.setFile(fileName);
    QListWidgetItem* item = new QListWidgetItem;
    item->setData(Qt::UserRole, fileinfo.absoluteFilePath());
    item->setText(fileinfo.fileName());
    ui->WidList->addItem(item);
    m_vecString.append(fileName);
    ui->stackedWidget->setCurrentIndex(1);
}

/*
 * date: 2023/8/16
 * author: brook
 * description: add all video files in the floder to the video list
*/
void MainWindow::addfloder()
{
    QString filename = QFileDialog::getExistingDirectory(this, "选择文件夹", "/home");
    QDir dir(filename);
    QStringList filter;
    filter << QString("*.mp4") << QString("*.avi")
           << QString("*.mkv") << QString("*.mp3")
           << QString("*.aac") << QString("*.mov")
           << QString("*.ts");
    dir.setNameFilters(filter);
    QList fileinfos = dir.entryInfoList(QDir::Files | QDir::CaseSensitive);
    if(fileinfos.isEmpty())
        return;
    for(int i = 0; i < fileinfos.count(); i++)
    {
        if(!m_vecString.contains(fileinfos[i].absoluteFilePath()))
        {
            QListWidgetItem* item = new QListWidgetItem;
            item->setData(Qt::UserRole, fileinfos[i].absoluteFilePath());
            item->setText(fileinfos[i].fileName());
            ui->WidList->addItem(item);
            m_vecString.append(fileinfos[i].absoluteFilePath());
        }
    }
    ui->stackedWidget->setCurrentIndex(1);
}

/*
 * date: 2023/8/16
 * author: brook
 * description: delete the selected item in the video list
*/
void MainWindow::deletefile()
{
    QList selectedItems = ui->WidList->selectedItems();
    if(selectedItems.isEmpty())
        return;
    QMessageBox msgBox;
    msgBox.setText("Are you sure to delete the selected files?");
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Yes);
    int ret = msgBox.exec();
    if(ret == QMessageBox::Yes)
    {
        for(int i = 0; i < selectedItems.count(); i++)
        {
            int index = m_vecString.indexOf(selectedItems[i]->data(Qt::UserRole));
            int row = ui->WidList->row(selectedItems[i]);
            QListWidgetItem* temp = ui->WidList->takeItem(row);
            delete temp;
            m_vecString.removeAt(index);
        }
    }
    else
        return;
}

/*
 * date: 2023/8/16
 * author: brook
 * description: fullscreen
*/
void MainWindow::fullscreen()
{
    if(!this->isFullScreen())
    {
        this->showFullScreen();
        ui->BtnFullscreen->setIcon(QIcon(":/icon/icon/zoom.png"));
    }
    else
    {
        this->showNormal();
        ui->BtnFullscreen->setIcon(QIcon(":/icon/icon/fill.png"));
    }
    m_vp_entrance->alter_video_size(ui->Widshow->width(), ui->Widshow->height());
}

/*
 * date: 2023/8/16
 * author: brook
 * description: impliment of double click fuction of items in QListWidget
*/
void MainWindow::itemsdoubleclick(QListWidgetItem* item)
{
    qDebug()<<"item double click";
    ui->CmbSpeed->setCurrentIndex(1);
    ui->Widshow->setSerial(ui->Widshow->serial() + 1);
    QString filename = item->data(Qt::UserRole).toString();
    if(m_vp_entrance->m_state == VpEntrance::PLAYING || m_vp_entrance->m_state == VpEntrance::PAUSE) {
        stopButton();
    }
    m_vp_entrance->start(filename.toStdString(), ui->Widshow->width(), ui->Widshow->height());
    ui->BtnPlay->setIcon(QIcon(":/icon/icon/pause.png"));
    m_pausecount = 1;
    ui->SldVideoSlider->setEnabled(true);
//    if(m_vp->m_PlayerState == videoplayer::Playing || m_vp->m_PlayerState == videoplayer::Pause)
//    {
//        m_vp->end();
//    }

//    m_vp->setfilename(filename.toStdString());
//    m_vp->start(ui->SldVolume->value());
//    m_totalSeconds = m_vp->get_video_alltime();

//    int hours = m_totalSeconds / 3600; // 计算小时数
//    int minutes = (m_totalSeconds % 3600) / 60; // 计算分钟数
//    int seconds = m_totalSeconds % 60; // 计算秒数

//    QTime time(hours, minutes, seconds);
//    ui->LabAlltime->setText(time.toString("hh:mm:ss"));
//    ui->SldVideoSlider->setMaximum(m_totalSeconds);
//    ui->SldVideoSlider->setMinimum(0);
}

void MainWindow::pausebutton()
{
    if(m_vp_entrance->m_state == VpEntrance::STOP)
        return;
    m_pausecount++;
    if(m_pausecount % 2 != 0)
    {
        ui->BtnPlay->setIcon(QIcon(":/icon/icon/pause.png"));
    }
    else
        ui->BtnPlay->setIcon(QIcon(":/icon/icon/play.png"));
    m_vp_entrance->pause_or_resume();
//    m_vp->pausebutton();
}

void MainWindow::alterCurSeconds(int curseconds)
{
//    int diff = curseconds - m_totalSeconds;
//    if( diff < 1 && diff > -1) curseconds = m_totalSeconds;
//    int hours = curseconds / 3600; // 计算小时数
//    int minutes = (curseconds % 3600) / 60; // 计算分钟数
//    int seconds = curseconds % 60; // 计算秒数

//    QTime time(hours, minutes, seconds);
//    ui->LabCurtime->setText(time.toString("hh:mm:ss"));
}

void MainWindow::audiobutton()
{
    if(m_audiobutton_count % 2 == 0)
    {
        ui->BtnMuteaudio->setIcon(QIcon(":/icon/icon/mute.png"));
        m_audiovolume_record = ui->SldVolume->value();
        ui->SldVolume->setValue(0);
        emit ui->SldVolume->sendTargetAudioVolume(0);
    }
    else
    {
        ui->BtnMuteaudio->setIcon(QIcon(":/icon/icon/aloud.png"));
        ui->SldVolume->setValue(m_audiovolume_record);
        int val = ui->SldVolume->value();
        emit ui->SldVolume->sendTargetAudioVolume(val);
    }
    m_audiobutton_count++;
}

void MainWindow::addThreeSecondsButton()
{
    int val = ui->SldVideoSlider->value() + 3;
    if(val > ui->SldVideoSlider->maximum()) val = ui->SldVideoSlider->maximum();
    emit sendTargetTime(val);
}
void MainWindow::minusThreeSecondsButton()
{
    int val = ui->SldVideoSlider->value() - 3;
    if(val < 0) val = 0;
    emit sendTargetTime(val);
}

void MainWindow::lastVideoButton()
{
    int cr =  ui->WidList->currentRow() - 1;
    if(cr < 0)
        cr = 0;
    ui->WidList->setCurrentRow(cr);
    QListWidgetItem* item = NULL;
    item = ui->WidList->currentItem();
    if(item)
        itemsdoubleclick(item);
}
void MainWindow::nextVideoButton()
{
    int cr =  ui->WidList->currentRow() + 1;
    if(cr >= ui->WidList->count())
        cr = ui->WidList->count() - 1;
    ui->WidList->setCurrentRow(cr);
    QListWidgetItem* item = NULL;
    item = ui->WidList->currentItem();
    if(item)
        itemsdoubleclick(item);
}

void MainWindow::stopButton()
{
    if(m_vp_entrance->m_state == VpEntrance::PAUSE) {
        pausebutton();
    }
    m_vp_entrance->stop();
    ui->SldVideoSlider->setEnabled(false);
}

void MainWindow::setSeconds(int seconds)
{
    int hours   = seconds / 3600; // 计算小时数
    int minutes = (seconds % 3600) / 60; // 计算分钟数
    int second  = seconds % 60; // 计算秒数

    QTime time(hours, minutes, second);
    ui->LabCurtime->setText(time.toString("hh:mm:ss"));
}

void MainWindow::setAllSeconds(int all_seconds)
{
    int hours   = all_seconds / 3600; // 计算小时数
    int minutes = (all_seconds % 3600) / 60; // 计算分钟数
    int second  = all_seconds % 60; // 计算秒数

    QTime time(hours, minutes, second);
    ui->LabAlltime->setText(time.toString("hh:mm:ss"));
}

void MainWindow::on_CmbSpeed_currentIndexChanged(int index)
{
    int cur_index = ui->CmbSpeed->currentIndex();
    switch (cur_index) {
    case 0:
        m_vp_entrance->alter_speed(0.5);
        break;
    case 1:
        m_vp_entrance->alter_speed(1.0);
        break;
    case 2:
        m_vp_entrance->alter_speed(1.5);
        break;
    case 3:
        m_vp_entrance->alter_speed(2.0);
        break;
    default:
        break;
    }
}


void MainWindow::on_BtnListbutton_clicked()
{
    ui->Widshow->setSerial(ui->Widshow->serial() + 1);
    if(ui->WidList->isHidden()) {
        ui->BtnListbutton->setIcon(QIcon(":/icon/icon/showList.png"));
        ui->BtnAddfile_2->show();
        ui->BtnAddfloder_2->show();
        ui->BtnDeletefile->show();
        ui->WidList->show();
        m_vp_entrance->alter_video_size(ui->Widshow->width(), ui->Widshow->height());
    } else {
        ui->BtnListbutton->setIcon(QIcon(":/icon/icon/hideList.png"));
        ui->BtnAddfile_2->hide();
        ui->BtnAddfloder_2->hide();
        ui->BtnDeletefile->hide();
        ui->WidList->hide();
        m_vp_entrance->alter_video_size(ui->stackedWidget->width(), ui->stackedWidget->height());
    }
}

